package com.ms.seguridad.service;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import java.util.Collection;
import java.util.Properties;

/**
 * Convierte URLs A Granted Autorities
 * La clase DpwcAuthenticationProviderImpl al momento de autenticar agrega como autority
 * Todas las opciones a las que el modulo tiene acceso
 * <p/>
 * Por ejemplo:
 * Usuario aochoa tiene como autorities las opciones: fnportal.jsf/fnopcion.jsf etc
 * <p/>
 * <p/>
 * User: AW
 * Date: 24/02/13
 */
public class DpwcSecureResourceFilter implements FilterInvocationSecurityMetadataSource {
    private Properties urlProperties;

    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    public Collection<ConfigAttribute> getAttributes(Object filter) {
        FilterInvocation filterInvocation = (FilterInvocation) filter;
        String url = filterInvocation.getRequestUrl();

        if (url.indexOf("public") < 0 && url.endsWith(".jsf") && url.indexOf("login") < 0 && url.indexOf("main") < 0) {
            int lastSlashIndex = url.lastIndexOf("/");
            url = "ROLE_" + url.substring(lastSlashIndex + 1, url.length() - 4);
            return SecurityConfig.createListFromCommaDelimitedString(url);
        }
        return getAttributesEstandar(filter);
    }

    public Collection<ConfigAttribute> getAttributesEstandar(Object filter)
            throws IllegalArgumentException {

        FilterInvocation filterInvocation = (FilterInvocation) filter;
        String url = filterInvocation.getRequestUrl();

        //get the roles for requested page from the property file
        String urlPropsValue = urlProperties.getProperty(url);
        StringBuilder rolesStringBuilder = new StringBuilder();
        if (urlPropsValue != null) {
            rolesStringBuilder.append(urlPropsValue).append(",");
        }

        if (!url.endsWith("/")) {
            int lastSlashIndex = url.lastIndexOf("/");
            url = url.substring(0, lastSlashIndex + 1);
        }

        String[] urlParts = url.split("/");
        StringBuilder urlBuilder = new StringBuilder();
        for (String urlPart : urlParts) {
            if (urlPart.trim().length() == 0) {
                continue;
            }
            urlBuilder.append("/").append(urlPart);
            urlPropsValue = urlProperties.getProperty(urlBuilder.toString() + "/**");
            if (urlPropsValue != null) {
                rolesStringBuilder.append(urlPropsValue).append(",");
            }
        }

        if (rolesStringBuilder.toString().endsWith(",")) {
            rolesStringBuilder.deleteCharAt(rolesStringBuilder.length() - 1);
        }
        if (rolesStringBuilder.length() == 0) {
            return null;
        }
        return SecurityConfig.createListFromCommaDelimitedString(rolesStringBuilder.toString());
    }

    public boolean supports(Class<?> arg0) {
        return true;
    }

    public void setUrlProperties(Properties urlProperties) {
        this.urlProperties = urlProperties;
    }

    public Properties getUrlProperties() {
        return urlProperties;
    }
}
